package cn.iocoder.yudao.module.product.evaluation.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.api.product.evaluation.ProductEvaluationApi;
import cn.iocoder.yudao.module.api.trade.order.TradeOrderApi;
import cn.iocoder.yudao.module.product.evaluation.dal.dataobject.ProductEvaluationDO;
import cn.iocoder.yudao.module.product.evaluation.service.ProductEvaluationService;
import cn.iocoder.yudao.module.product.evaluation.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 产品评价")
@RestController
@RequestMapping("/product/comment")
@Validated
public class AppProductEvaluationController {

    @Resource
    private ProductEvaluationService productEvaluationService;

    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private ProductEvaluationApi productEvaluationApi;
    @Resource
    private TradeOrderApi tradeOrderApi;

    @PostMapping("/create")
    @Operation(summary = "买家添加产品评价")
    public CommonResult<Long> createComment(@RequestBody AppProductEvaluationCreateReqVO createReqVO) {
        //return success(productCommentService.createComment(getLoginUserId(), createReqVO));
        // 使用交易订单模块的实现以便改变订单评价状态并记录订单日志
        return success(tradeOrderApi.createOrderCommentByMember(getLoginUserId(), createReqVO));
    }

    @PostMapping("/append")
    @Operation(summary = "买家追加产品评价")
    public CommonResult<Boolean> appendComment(@RequestBody AppProductEvaluationAppendReqVO appendReqVO) {
        productEvaluationService.appendComment(appendReqVO);
        return success(true);
    }

    @PostMapping("/reply")
    @Operation(summary = "卖家回复产品评价")
    public CommonResult<Boolean> commentReply(@Valid @RequestBody AppProductEvaluationReplyReqVO replyVO) {
        productEvaluationService.replyComment(replyVO);
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得产品评价分页")
    @PermitAll
    public CommonResult<PageResult<AppProductEvaluationRespVO>> getCommentPage(@Valid AppProductEvaluationPageReqVO pageVO) {
        // TODO 按订单分组，订单下的多个产品合并
        PageResult<ProductEvaluationDO> pageResult = productEvaluationService.getCommentPage(pageVO, Boolean.TRUE);
        return toPageResultCommonResult(pageResult, true);
    }

    @GetMapping("/get-count")
    @Operation(summary = "获得产品评价数量")
    @Parameter(name = "shopId", description = "店铺编号")
    @PermitAll
    public CommonResult<Map<String, Integer>> getOrderCommentCount(@RequestParam("shopId") Long shopId) {
        return success(productEvaluationApi.getCommentCount(shopId));
    }

    @GetMapping("/my-page")
    @Operation(summary = "获得我的产品评价分页")
    public CommonResult<PageResult<AppProductEvaluationRespVO>> getMyCommentPage(@Valid PageParam pageVO) {
        PageResult<ProductEvaluationDO> pageResult = productEvaluationService.getMyCommentPage(getLoginUserId(), pageVO);
        return toPageResultCommonResult(pageResult, false);
    }

    private CommonResult<PageResult<AppProductEvaluationRespVO>> toPageResultCommonResult(PageResult<ProductEvaluationDO> pageResult, boolean includeUserInfo) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        PageResult<AppProductEvaluationRespVO> result = BeanUtils.toBean(pageResult, AppProductEvaluationRespVO.class);
        if (!includeUserInfo) {
            return success(result);
        }
        Set<Long> userIds = pageResult.getList().stream().map(ProductEvaluationDO::getUserId).collect(Collectors.toSet());
        Map<Long, UserSimpleVO> users = memberUserApi.getUserSimpleMap(userIds);
        // 拼接返回
        result.getList().forEach(item -> {
            if (Boolean.TRUE.equals(item.getAnonymous())) {
                item.setUser(UserSimpleVO.ANONYMOUS);
            } else {
                item.setUser(users.get(item.getUserId()));
            }
        });
        return success(result);
    }

    @GetMapping("/delete")
    @Operation(summary = "买家删除自己的评价")
    @Parameter(name = "id", description = "评价编号", required = true)
    public CommonResult<Boolean> deleteComment(@RequestParam("id") Long id) {
        productEvaluationService.deleteComment(getLoginUserId(), id);
        return success(true);
    }

}
